package com.jiyun.passenger.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jiyun.passenger.mapper.OrderInfoMapper;
import com.jiyun.passenger.service.OrderInfoService;
import com.jiyun.pojo.CarType;
import com.jiyun.pojo.OperatePassengerCharges;
import com.jiyun.pojo.Personal;
import com.jiyun.pojo.order.*;
import com.jiyun.pojo.order.vo.*;
import com.jiyun.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderInfoServiceImpl implements OrderInfoService {
    @Autowired
    OrderInfoMapper orderInfoMapper;

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    RedisTemplate redisTemplate;

    @Transactional
    @Override
    public Result addOrderInfo(OrderInfoVo orderInfoVo) {
        try {
            // 查询出原始订单
            OrderInformation orderInformation1 = orderInfoMapper.findByOrderInfoId(orderInfoVo.getOrderInformation());
            log.info("原始订单信息：{}", orderInformation1);
            if (!ObjectUtils.isEmpty(orderInformation1)) {
                throw new RuntimeException("当前乘客存在未支付的订单");
            }
            OrderInformation orderInformation = new OrderInformation();
            // 订单属性赋值
            // 生成订单号
            String orderId = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
            orderInformation.setOrderId(orderId);
            orderInformation.setOrderStatus(0);
            orderInformation.setCityId(1);
            orderInformation.setStartingPoint(orderInfoVo.getOrderInformation().getStartingPoint());
            orderInformation.setDestination(orderInfoVo.getOrderInformation().getDestination());
            orderInformation.setStartingPointAddress(orderInfoVo.getOrderInformation().getStartingPointAddress());
            orderInformation.setDestinationAddress(orderInfoVo.getOrderInformation().getDestinationAddress());
            orderInformation.setOrderType(3);
            orderInformation.setOrderMileage(orderInfoVo.getOrderInformation().getOrderMileage());

            orderInformation.setUserId(orderInfoVo.getOrderInformation().getUserId());
            // 司机接客验证码是乘客手机号后四位
            Personal personal = orderInfoMapper.findByUser(orderInfoVo.getOrderInformation());
            orderInformation.setPassengerName(personal.getFareName());
            orderInformation.setPassengerPhone(personal.getFarePhone());
            if (personal.getFarePhone().length() >= 4) {
                String randomCode = personal.getFarePhone().substring(personal.getFarePhone().length() - 4);
                orderInformation.setRandomCode(Integer.valueOf(randomCode));
            }

            OrderTime orderTime = new OrderTime();
            orderTime.setOrderId(orderId);
            // 判断时间是否为空 如果为空，则默认为当前时间
            if (orderInfoVo.getOrderTime().getOrderTime() == null) {
                orderTime.setOrderTime(new Date());
            } else {
                // 时间不为空
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = sdf.format(orderInfoVo.getOrderTime().getOrderTime());
                Date orderTime2 = null;
                orderTime2 = sdf.parse(format);
                log.info("orderTime2:{}", orderTime2);
                orderTime.setOrderTime(orderTime2);


            }


            // 将 Date 转换为字符串
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateString = sdf.format(orderTime.getOrderTime());

            // 解析字符串为 LocalDate
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate date = LocalDate.parse(dateString, formatter);

            // 获取星期几
            DayOfWeek dayOfWeek = date.getDayOfWeek();
            String chineseDayOfWeek = convertToChinese(dayOfWeek);
            orderTime.setDayOfTheWeek(chineseDayOfWeek);

            orderInfoMapper.saveOrderTimeOnOrderTime(orderTime);
            // 起步价+(公里数*单价)+(等待超出时间*单价)+违约金+违约金
            OperatePassengerCharges operatePassengerCharges = orderInfoMapper.findByOperatePassengerCharges();
            BigDecimal orderMileage = new BigDecimal(orderInformation.getOrderMileage());
            BigDecimal startingKilometer = BigDecimal.valueOf(operatePassengerCharges.getStartingKilometer());

            BigDecimal estimatedPrice = null;
            // 使用 BigDecimal 的 subtract 方法来执行减法操作
            if (orderMileage != null && startingKilometer != null) {
                BigDecimal mileageDifference = orderMileage.subtract(startingKilometer);
                estimatedPrice = mileageDifference.multiply(operatePassengerCharges.getMileageFee())
                        .add(operatePassengerCharges.getStartingPrice());
            }
            log.info("预估价：{}", estimatedPrice);

            OrderCost orderCost = new OrderCost();
            orderCost.setOrderId(orderId);
            orderCost.setOrderMoney(orderCost.getOrderMoney());
            orderCost.setPayStatus(0);
            orderCost.setPreferentialMoney(BigDecimal.valueOf(0));
            orderCost.setEstimatedPrice(estimatedPrice);
            orderCost.setBaggageFee(BigDecimal.valueOf(0));
            orderCost.setExpenses(BigDecimal.valueOf(0));
            orderCost.setEstimatedPrice(orderCost.getEstimatedPrice());
            orderInfoMapper.saveOrderCost(orderCost);

            String orderInfo = (String) redisTemplate.opsForValue().get("passenger");
            OrderInfoVo orderInfoVo2 = JSON.parseObject(orderInfo, OrderInfoVo.class);
            if (orderInfoVo2 != null) {
                orderInformation.setPassengerName(orderInfoVo2.getPassengerName());
                orderInformation.setPassengerPhone(orderInfoVo2.getPassengerPhone());
                redisTemplate.delete("passenger");
            }
            // 4.插入订单
            int insert = orderInfoMapper.addOrderInfo(orderInformation);
            log.info("插入订单信息：{}", insert);
            if (insert != 1) {
                return Result.error("下单失败");
            }
            OrderInformation orderInformation2 = orderInfoMapper.selectOrderByOrderId(orderId);
            rabbitTemplate.convertAndSend("orderProcessing", orderInformation2.getId() + "");
            rabbitTemplate.convertAndSend("suibian", orderInformation2.getOrderId() + "");
            redisTemplate.opsForValue().set("orderProcessing", orderInformation2.getId() + "", 30, TimeUnit.MINUTES);
            redisTemplate.opsForValue().set("suibian", orderId + "", 30, TimeUnit.MINUTES);

            return Result.ok(orderId);

        } catch (Exception e) {
            return Result.error(e.getMessage());
        }

    }

    private String convertToChinese(DayOfWeek dayOfWeek) {
        switch (dayOfWeek) {
            case MONDAY:
                return "周一";
            case TUESDAY:
                return "周二";
            case WEDNESDAY:
                return "周三";
            case THURSDAY:
                return "周四";
            case FRIDAY:
                return "周五";
            case SATURDAY:
                return "周六";
            case SUNDAY:
                return "周日";
            default:
                return "未知";
        }
    }


    public OperatePassengerCharges findByMileageFee() {
        return orderInfoMapper.findByMileageFee();
    }

    @Override
    public OrderInformation findByOrder(OrderInformation orderInformation) {
        return orderInfoMapper.findByOrder(orderInformation);
    }

    @Override
    public OrderTime findByOrderIdTime(OrderTime orderTime) {
        return orderInfoMapper.findByOrderIdTime(orderTime);
    }


}
